package com.lb.videoplay.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;

import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.lb.videoplay.R;
import com.lb.videoplay.adapter.HobbyAdapter;
import com.lb.videoplay.model.IndustryModel;
import com.lb.videoplay.model.UserInfoModel;
import com.lb.videoplay.statuslib.StatusUtil;
import com.lb.videoplay.utils.BackgroundDarkPopupWindow;
import com.lb.videoplay.utils.CircleImageView;
import com.lb.videoplay.utils.CodeUtils;
import com.lb.videoplay.utils.CommonUtils;
import com.lb.videoplay.utils.LQRPhotoSelectUtils;
import com.lb.videoplay.utils.SharedPref;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.addapp.pickers.picker.SinglePicker;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;


/**
 * Created by Mr.lb
 * 时间： 2018/11/27
 * 包名： com.lb.videoplay.activity
 * 描述： 注册
 */
public class RegisterActivity extends FragmentActivity implements View.OnClickListener {

    private TextView mLeftTitleIcon;
    private TextView mCenterTitle;
    private LinearLayout mRlBg;
    private ImageView mIvHead;
    private CircleImageView mIvUserHead;
    private EditText mEtUserName;
    private RadioButton mRbGender;
    private TextView mTvMethod;
    private EditText mEtUserPhone;
    private ImageView mIvClose;
    private ImageView mIvCloses;
    private EditText mEtUserPhoneCode;
    private TextView mEtUserIndustry;
    private LinearLayout mLlIndustry;
    private TextView mEtUserHobby;
    private LinearLayout mLlHobby;
    private Button mBtRegisterNext;
    private ImageView mIvCode;
    private EditText mPosition;

    private LQRPhotoSelectUtils mLqrPhotoSelectUtils;
    private CodeUtils codeUtils;
    private List<String> list;
    private BackgroundDarkPopupWindow mPopupWindow;
    private HobbyAdapter mAdapter;
    private List<IndustryModel.HobbiesBean> mHobbies;
    private List<IndustryModel.HobbiesBean> ltHobbies;
    public int Count = 0;
    private String mUserBase64;
    private CommonUtils mCommonUtils;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        SwipeBackHelper.onCreate(this);  //右侧滑动退出
        initWidget();
        initEvent();
        initTitle();
        init();
        getCode();
        initData();
        mCommonUtils = new CommonUtils(this);
    }

    private void initData() {
        ltHobbies = new ArrayList<>();
        ltHobbies.clear();
        IndustryModel.HobbiesBean mhobbies = new IndustryModel.HobbiesBean();
        mhobbies.setHobbyName("高尔夫");
        ltHobbies.add(mhobbies);

        IndustryModel.HobbiesBean mhobbies1 = new IndustryModel.HobbiesBean();
        mhobbies1.setHobbyName("旅游");
        ltHobbies.add(mhobbies1);

        IndustryModel.HobbiesBean mhobbies2 = new IndustryModel.HobbiesBean();
        mhobbies2.setHobbyName("网球");
        ltHobbies.add(mhobbies2);

        IndustryModel.HobbiesBean mhobbies3 = new IndustryModel.HobbiesBean();
        mhobbies3.setHobbyName("沙龙论坛");
        ltHobbies.add(mhobbies3);

        IndustryModel.HobbiesBean mhobbies4 = new IndustryModel.HobbiesBean();
        mhobbies4.setHobbyName("游艇");
        ltHobbies.add(mhobbies4);

        IndustryModel.HobbiesBean mhobbies5 = new IndustryModel.HobbiesBean();
        mhobbies5.setHobbyName("美酒");
        ltHobbies.add(mhobbies5);

        IndustryModel.HobbiesBean mhobbies6 = new IndustryModel.HobbiesBean();
        mhobbies6.setHobbyName("美食");
        ltHobbies.add(mhobbies6);

        IndustryModel.HobbiesBean mhobbies7 = new IndustryModel.HobbiesBean();
        mhobbies7.setHobbyName("超跑");
        ltHobbies.add(mhobbies7);

        IndustryModel.HobbiesBean mhobbies8 = new IndustryModel.HobbiesBean();
        mhobbies8.setHobbyName("航空");
        ltHobbies.add(mhobbies8);

        IndustryModel.HobbiesBean mhobbies9 = new IndustryModel.HobbiesBean();
        mhobbies9.setHobbyName("智能");
        ltHobbies.add(mhobbies9);

        IndustryModel.HobbiesBean mhobbies10 = new IndustryModel.HobbiesBean();
        mhobbies10.setHobbyName("珠宝");
        ltHobbies.add(mhobbies10);

        if (mHobbies == null || mHobbies.size() == 0)
            mHobbies = ltHobbies;
    }

    //初始化标题
    public void initTitle() {
        // 第二个参数是是否沉浸,第三个参数是状态栏字体是否为黑色
        StatusUtil.setSystemStatus(this, true, true);
        mCenterTitle.setText(getText(R.string.app_login_register_title));
        Drawable nav_up = getResources().getDrawable(R.drawable.back);
        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
        mLeftTitleIcon.setCompoundDrawables(null, null, nav_up, null);
    }


    public void initWidget() {
        mLeftTitleIcon = findViewById(R.id.left_title_icon);
        mCenterTitle = findViewById(R.id.center_title);
        mRlBg = findViewById(R.id.rl_bg);
        mIvHead = findViewById(R.id.iv_head);
        mIvUserHead = findViewById(R.id.iv_user_head);
        mEtUserName = findViewById(R.id.ed_user_name);
        mRbGender = findViewById(R.id.rb_gender);
        mTvMethod = findViewById(R.id.tv_method);
        mEtUserPhone = findViewById(R.id.ed_user_phone);
        mIvClose = findViewById(R.id.iv_close);
        mIvCloses = findViewById(R.id.iv_closes);
        mEtUserPhoneCode = findViewById(R.id.ed_user_phone_code);
        mEtUserIndustry = findViewById(R.id.ed_user_industry);
        mLlIndustry = findViewById(R.id.ll_industry);
        mEtUserHobby = findViewById(R.id.ed_user_hobby);
        mLlHobby = findViewById(R.id.ll_hobby);
        mBtRegisterNext = findViewById(R.id.bt_register_next);
        mIvCode = findViewById(R.id.iv_code);
        mPosition = findViewById(R.id.ed_user_position);
    }

    public void initEvent() {
        mLeftTitleIcon.setOnClickListener(this);
        mIvHead.setOnClickListener(this);
        mIvUserHead.setOnClickListener(this);
        mTvMethod.setOnClickListener(this);
        mIvClose.setOnClickListener(this);
        mLlIndustry.setOnClickListener(this);
        mLlHobby.setOnClickListener(this);
        mIvCode.setOnClickListener(this);
        mBtRegisterNext.setOnClickListener(this);

        //监听手机号码
        mEtUserPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    // if (Kits.Random.isChinaPhoneLegal(ed_update_number.getText().toString())) {
                  /*  if (!isRes) {
                        mBtGetCode.setBackgroundResource(R.drawable.button_login);
                        mBtGetCode.setEnabled(true);
                        mIvClose.setVisibility(View.VISIBLE);
                        mIvClose.setEnabled(true);
                    }*/
                    //}
                } else {
                    mIvClose.setVisibility(View.GONE);
                    mIvClose.setEnabled(false);
                }
            }
        });
        //监听密码框
        mEtUserName.addTextChangedListener(mTextWatcher);
        mEtUserPhoneCode.addTextChangedListener(mTextWatcher);
        mEtUserPhone.addTextChangedListener(mTextWatcher);
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mEtUserName.length() > 0 && mEtUserPhoneCode.length() > 0 && mEtUserPhone.length() > 0) {
                mBtRegisterNext.setBackgroundResource(R.drawable.button_login);
                mBtRegisterNext.setEnabled(true);
            } else {
                mBtRegisterNext.setBackgroundResource(R.drawable.bt_width_select);
                mBtRegisterNext.setEnabled(false);
            }
        }
    };

    //获取验证码
    private void getCode() {
        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        mIvCode.setImageBitmap(bitmap);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        SwipeBackHelper.onPostCreate(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_title_icon://返回
                finish();
                break;
            case R.id.iv_code: //获取验证码
                getCode();
                break;
            case R.id.iv_head://更换头像
                bottomDialog();
                break;
            case R.id.iv_user_head://更换头像
                bottomDialog();
                break;
            case R.id.iv_close: //清空
                mEtUserPhone.setText("");
                break;
            case R.id.ll_industry://选择行业
                onConstellationPicker();
                break;
            case R.id.ll_hobby://选择爱好
                initPopupWindow();
                break;
            case R.id.bt_register_next://注册
                setRegister(mUserBase64, mEtUserName.getText().toString(), mEtUserPhone.getText().toString(),
                        mEtUserPhoneCode.getText().toString(), mPosition.getText().toString()
                        , mEtUserIndustry.getText().toString(), mEtUserHobby.getText().toString());

                break;
        }
    }

    //注册
    private void setRegister(String mUserBase64, String userName,
                             String phone, String phoneCode, String
                                     mPosition, String mEtUserIndustry, String mEtUserHobby) {
        if (ObjectUtils.isEmpty(mUserBase64)) {
            ToastUtils.showShort("您忘记设置的头像咯");
            return;
        }
        if (ObjectUtils.isEmpty(userName)) {
            ToastUtils.showShort("您忘记填写名字咯");
            return;
        }
        if (ObjectUtils.isEmpty(phone)) {
            ToastUtils.showShort("您忘记填写联系方式咯");
            return;
        }
        if (!mCommonUtils.isChinaPhoneLegal(phone)) {
            ToastUtils.showShort("您的手机号码格式有误");
            return;
        }
        if (ObjectUtils.isEmpty(phoneCode)) {
            ToastUtils.showShort("您忘记填写验证码咯");
            return;
        }
        String code = codeUtils.getCode();
        if (!code.equalsIgnoreCase(phoneCode)) {
            ToastUtils.showShort("您输入验证码有误");
            getCode();
            return;
        }
        if (ObjectUtils.isEmpty(mPosition)) {
            ToastUtils.showShort("您忘记设置密码咯");
            return;
        }
        if (mPosition.length() < 6) {
            ToastUtils.showShort("密码长度必须大于6位");
            return;
        }
        mCommonUtils.showLoadDialog("注册");
        SPUtils.getInstance().put("phone", phone);
        SPUtils.getInstance().put("pwd", mPosition);
        SPUtils.getInstance().put("userName", userName);
        SPUtils.getInstance().put("userhead", mUserBase64);
        SPUtils.getInstance().put("isLogin",true);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                mCommonUtils.dissDialog();
                ActivityUtils.startActivity(MainActivity.class);
                finish();
            }
        }, 2000);


    }

    /**
     * PopupWindow
     */
    private void initPopupWindow() {
        View view = View.inflate(this, R.layout.item_popup, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        final RecyclerView recyclerView = view.findViewById(R.id.rv_industry);

        mPopupWindow = new BackgroundDarkPopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(false);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setAnimationStyle(R.style.DarkAnimation);
        mPopupWindow.setDarkStyle(-1);
        mPopupWindow.setDarkColor(Color.parseColor("#a0000000"));
        mPopupWindow.resetDarkPosition();
        mPopupWindow.darkBelow(mRlBg);
        mPopupWindow.showAsDropDown(mRlBg, mRlBg.getRight() / 2, 0);

        mAdapter = new HobbyAdapter(R.layout.item_hobby, ltHobbies);

        //填充adapter
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view1, int position) {
                if (R.id.ll_select == view1.getId()) {
                    IndustryModel.HobbiesBean hobbiesBean = (IndustryModel.HobbiesBean) adapter.getData().get(position);
                    mAdapter.changeSelected(position);
                    if (Count > 2) {
                        if (!hobbiesBean.isSelect()) {
                            ToastUtils.showLong("您最多只能选择3个");
                        } else {
                            hobbiesBean.setSelect(false);
                            Count = Count - 1;
                        }
                    } else {
                        if (!hobbiesBean.isSelect()) {
                            hobbiesBean.setSelect(true);
                            Count = Count + 1;
                        } else {
                            hobbiesBean.setSelect(false);
                            Count = Count - 1;
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        LinearLayoutManager ms = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(ms);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);


        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();

            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mHobbies.size(); i++) {
                    if (mHobbies.get(i).isSelect()) {
                        if (sb.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                            sb.append(",");
                        }
                        sb.append(mHobbies.get(i).getHobbyName());
                    }
                }
                mEtUserHobby.setText(String.format("%s", sb.toString()));
            }
        });
        tv_title.setText(getString(R.string.app_login_user_hobby_hint));
    }

    //职业
    public void onConstellationPicker() {
        list = new ArrayList<>();
        list.clear();
        list.add("消费服务");
        list.add("地产开发");
        list.add("私募股权投资");
        list.add("纺织/服饰");
        list.add("计算机软件");
        list.add("顾问/咨询");
        list.add("医药/健康");
        list.add("农林牧渔");
        list.add("高端消费");
        list.add("交通运输/物流仓储");
        list.add("能源/化工");
        list.add("航空/汽车");
        list.add("综合企业集团");
        list.add("O2O平台");
        SinglePicker<String> picker = new SinglePicker<>(this, list);

        picker.setCanLoop(true);//不禁用循环
        picker.setTopBackgroundColor(getResources().getColor(R.color.baseres_color_line));
        picker.setTopHeight(50);
        /*picker.setTopLineColor(0xFF33B5E5);
        picker.setTopLineHeight(1);*/
        // picker.setTitleText(isChinese ? "请选择" : "Please pick");
        picker.setCancelTextColor(getResources().getColor(R.color.baseres_size_color_three_title));
        picker.setCancelTextSize(12);
        picker.setSubmitTextColor(getResources().getColor(R.color.baseres_bt_color));
        picker.setSubmitTextSize(12);
        picker.setSelectedTextColor(getResources().getColor(R.color.baseres_size_color_one_title));
        picker.setUnSelectedTextColor(getResources().getColor(R.color.baseres_size_color_three_title));
        picker.setWheelModeEnable(false);
        // LineConfig config = new LineConfig();
        //config.setColor(Color.BLUE);//线颜色
        // config.setAlpha(120);//线透明度
//        config.setRatio(1);//线比率
        // picker.setLineConfig(config);
        picker.setItemWidth(200);
        picker.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        //picker.setSelectedItem(isChinese ? "处女座" : "Virgo");
        // picker.setSelectedIndex(0);
        picker.setOnItemPickListener((index, item) -> mEtUserIndustry.setText(String.format("%s", item)));
        picker.show();
    }

    protected void onDestroy() {
        super.onDestroy();
        SwipeBackHelper.onDestroy(this);
        mLqrPhotoSelectUtils = null;
        if (list != null) {
            list.clear();
            list = null;
        }
        if (mHobbies != null)
            mHobbies = null;
        if (mPopupWindow != null)
            mPopupWindow = null;
        if (ltHobbies != null) {
            ltHobbies.clear();
            ltHobbies = null;
        }

    }

    private void init() {
        // 1、创建LQRPhotoSelectUtils（一个Activity对应一个LQRPhotoSelectUtils）
        mLqrPhotoSelectUtils = new LQRPhotoSelectUtils(this, new LQRPhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri) {
                // 4、当拍照或从图库选取图片成功后回调
                mIvHead.setVisibility(View.GONE);
                mIvUserHead.setVisibility(View.VISIBLE);
                RequestOptions requestOptions = new RequestOptions()
                        .placeholder(R.drawable.head)
                        .error(R.drawable.head)
                        .fallback(R.drawable.head);
                Glide.with(RegisterActivity.this).load(outputUri).apply(requestOptions).into(mIvUserHead);
                try {
                    mUserBase64 = mCommonUtils.encodeBase64File(outputFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, true);//true裁剪，false不裁剪
    }

    public void bottomDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.item_industry)     //设置dialog布局文件
                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setText(R.id.tv_mes, getString(R.string.app_login_camera));
                        holder.setText(R.id.tv_method, getString(R.string.app_login_album));
                        holder.setOnClickListener(R.id.ll_camera, new View.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                            @Override
                            public void onClick(View v) {
                                //调用相机
                                PermissionGen.with(RegisterActivity.this)
                                        .addRequestCode(LQRPhotoSelectUtils.REQ_TAKE_PHOTO)
                                        .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                Manifest.permission.CAMERA
                                        ).request();
                                dialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.ll_album, new View.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                            @Override
                            public void onClick(View v) {
                                // 3、调用从图库选取图片方法
                                PermissionGen.needPermission(RegisterActivity.this,
                                        LQRPhotoSelectUtils.REQ_SELECT_PHOTO,
                                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                                Manifest.permission.WRITE_EXTERNAL_STORAGE}
                                );
                                dialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.ll_cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                .setShowBottom(true)     //是否在底部显示dialog，默认flase
                //.setMargin(0)     //dialog左右两边到屏幕边缘的距离（单位：dp），默认0dp
                //.setWidth()     //dialog宽度（单位：dp），默认为屏幕宽度，-1代表WRAP_CONTENT
                //.setHeight(-1)     //dialog高度（单位：dp），默认为WRAP_CONTENT
                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                .setAnimStyle(R.style.ActionSheetDialogAnimation)//设置dialog进入、退出的动画style(底部显示的dialog有默认动画)
                .show(getSupportFragmentManager());//显示dialog
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 2、在Activity中的onActivityResult()方法里与LQRPhotoSelectUtils关联
        mLqrPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    @PermissionSuccess(requestCode = LQRPhotoSelectUtils.REQ_TAKE_PHOTO)
    private void takePhoto() {
        mLqrPhotoSelectUtils.takePhoto();
    }

    @PermissionSuccess(requestCode = LQRPhotoSelectUtils.REQ_SELECT_PHOTO)
    private void selectPhoto() {
        mLqrPhotoSelectUtils.selectPhoto();
    }

    @PermissionFail(requestCode = LQRPhotoSelectUtils.REQ_TAKE_PHOTO)
    private void showTip1() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    @PermissionFail(requestCode = LQRPhotoSelectUtils.REQ_SELECT_PHOTO)
    private void showTip2() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    public void showDialog() {
        //创建对话框创建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框显示小图标
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        //设置标题
        builder.setTitle("权限申请");
        //设置正文
        builder.setMessage("在设置-应用-金品汇-权限 中开启相机、存储权限，才能正常使用拍照或图片选择功能");

        //添加确定按钮点击事件
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {//点击完确定后，触发这个事件

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //这里用来跳到手机设置页，方便用户开启权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + RegisterActivity.this.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        //添加取消按钮点击事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        //使用构建器创建出对话框对象
        AlertDialog dialog = builder.create();
        dialog.show();//显示对话框
    }

}
